package br.cefet.farmaciaonline.servlet;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import br.cefet.farmaciaonline.dao.MedicamentoDAO;
import br.cefet.farmaciaonline.util.Convertion;
import br.cefet.farmaciaonline.vo.Medicamento;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;



/**
 * Servlet implementation class MedicamentoServlet
 */

public class MedicamentoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	 // upload settings
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
	
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MedicamentoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 String cmd = request.getParameter("operacao");
	        
	     System.out.println("CMD: "+cmd);
	     
	     if (cmd == null  || cmd.equals("cadastro") ) {
	    	 
	    	 cadastroMedicamento(request,response);
	    	 
	     } else if ( cmd == null  || cmd.equals("pesquisa") ){
	    	 pesquisaMedicamentos(request,response);
	    	 
	     } if (cmd != null  && cmd.equals("imagem") ) {
	    	 
	    	 imagemMedicamento(request,response);
	    	 
	     }
		
		
	}
	

	private void imagemMedicamento(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String param = request.getParameter("idMedicamento");
		int idMedicamento = Integer.parseInt(param);
		
		Medicamento medicamento = MedicamentoDAO.getInstance().getImagemById(idMedicamento);
		
		
		response.setContentType("image/jpeg");
		
		if (medicamento != null && medicamento.getImagem() !=null) {
			response.setContentType("image/jpeg");		
			response.setContentLength(medicamento.getImagem().length);		
			response.getOutputStream().write(medicamento.getImagem());
		}	

		
	}

	private void pesquisaMedicamentos(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		 String param = request.getParameter("query");
		 
		 List<Medicamento> listaMedicamentos = MedicamentoDAO.getInstance().pesquisa(param);
		 
		 request.setAttribute("listaMedicamentos", listaMedicamentos);
		 request.setAttribute("paramPesquisa", param);
		 
		 System.out.print("listaMedicamentos.size ="+listaMedicamentos.size());
		 
		 request.getRequestDispatcher("Busca.jsp").forward(request, response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}
	
	
	private void cadastroMedicamento(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {
		
		
		
		
		
		// TODO Auto-generated method stub
		if (!ServletFileUpload.isMultipartContent(request)) {
            // if not, we stop here
            PrintWriter writer = response.getWriter();
            writer.println("Error: Form deveria ser enctype=multipart/form-data.");
            writer.flush();
            return;
        }
		
		
		
		
		Medicamento medicamento = new Medicamento();
		
				
		
		//DiskFileItemFactory factory = new DiskFileItemFactory();
		//MultipartStream ms = new MultipartStream(request.getInputStream(),getBoundary(""));
		// configures upload settings
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // sets memory threshold - beyond which files are stored in disk 
        factory.setSizeThreshold(MEMORY_THRESHOLD);
        // sets temporary location to store files
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
 
        ServletFileUpload upload = new ServletFileUpload(factory);
         
        // sets maximum size of upload file
        upload.setFileSizeMax(MAX_FILE_SIZE);
         
        // sets maximum size of request (include file + form data)
        upload.setSizeMax(MAX_REQUEST_SIZE);
        
        
		
		try {
			
			
			List<FileItem> formItems = upload.parseRequest(request);
			
			
			if (formItems != null && formItems.size() > 0) {
                // iterates over form's fields
                for (FileItem item : formItems) {
                    // processes only fields that are not form fields
                    if (!item.isFormField()) {
                        //String fileName = new File(item.getName()).getName();
                        //String filePath = uploadPath + File.separator + fileName;
                        //File storeFile = new File(filePath);
 
                        // get the InputStream
                        //item.getInputStream();
                    	//ArrayList<StarData> starData  = DataReader.loadFromInputStream(item.getInputStream());
                    	//request.getSession().setAttribute("starData", starData);
                    	//byte[] bt  = 
                    	
                    	//byte[] bin  = item.getInputStream().
                    	BufferedImage image = loadImageFromInputStream(item.getInputStream());
                    	byte[] imageb = imageToByteArray(image); 
                    	medicamento.setImagem(imageb);
                    	
                    	
                        request.setAttribute("msg","Arquivo Carregado!");
                    } else {
                    	
                    	               			
                    	
                    	if (item.getFieldName().equals("nome")) {
                    		medicamento.setNome(item.getString());
                    	} else if (item.getFieldName().equals("descricao")) {
                    		medicamento.setDescricao(item.getString());
                    	} else if (item.getFieldName().equals("preco")) {
                    		medicamento.setPreco(Double.parseDouble(item.getString()));//Convertion.stringToDouble(item.getString().toString()));
                    	} else if (item.getFieldName().equals("principioAtivo")) {
                    		medicamento.setPrincipioAtivo(item.getString());
                    	}
                    	
                    }
                    
                    
                    
                }
            }
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		 
		
		MedicamentoDAO.getInstance().inserir(medicamento);
		
		request.setAttribute("msg","Medicamento cadastrado com sucesso!");
		
		request.getRequestDispatcher("CadastroMedicamento.jsp").forward(request, response);
		
		
		
		
		
	}
	
	
    //carrega imagem do arquivo
	private static byte[] imageToByteArray(BufferedImage image)
			throws ImageFormatException, IOException {
		//BufferedInputStream in = new BufferedInputStream(new FileInputStream(fileName));
		//Image result = loadImageFromInputStream(in);
		//return result;
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(baos);
		encoder.encode(image);
		return baos.toByteArray();		
		
	}
	
	
	

	//carrega imagem de um inputStream. Proprio para uso dentro de action web  
	private static BufferedImage loadImageFromInputStream(InputStream in) throws IOException {
		JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
		BufferedImage result = decoder.decodeAsBufferedImage();
		return result;
	}


}
